<template>
  <div class="form_dialog">
    <!--
      composion 语法 通用弹框模板

        使用方法：全部复制，粘贴，根据业务需求修改，多余的删掉

        属性：
        preparedData

        事件：
        @close // 当弹窗关闭
        @submitSuccess // 当提交成功

        父组件调用（采用调用方法的方式打开，保证数据传递及时性，以及方便控制打开时的初始化逻辑处理，且父组件无需维护多余子组件的变量）：

          组件标签：
          <Vue2FormDialogTemplate :preparedData="formDialogPreparedData" @close="onClose" @submitSuccess="onSubmitSuccess"/>

          打开：
          this.$refs.vue2FormDialogTemplate?.open() // 新增
          this.$refs.vue2FormDialogTemplate?.open(row) // 编辑

          关闭：
          this.$refs.vue2FormDialogTemplate?.close()

     -->
    <el-dialog
      v-model="visible"
      :append-to-body="true"
      :show-close="true"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :title="`${isEdit ? '编辑' : '新建'}模板弹框`"
      width="60%"
      @closed="close"
    >
      <div v-loading="dialogLoading">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="form">
          <el-form-item label="示例一：" prop="propOne">
            <el-input v-model="formData.propOne" placeholder="请输入" clearable></el-input>
          </el-form-item>

          <el-form-item label="示例二：" prop="propTwo">
            <el-select v-model.trim="formData.propTwo" placeholder="请选择" filterable clearable>
              <el-option
                v-for="(cell, j) in preparedData.propTwoSelectList"
                :key="cell.val"
                :value="cell.val"
                :label="cell.label"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit" :loading="btnLoading">确定</el-button>
          <el-button @click="close" :disabled="btnLoading">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
// import { useLoginStore } from '@/stores/modules/login'
import { useRouter } from 'vue-router'
import { ResponseData } from '#/global'

const { proxy } = getCurrentInstance() as any
const $api = proxy.$api
const $statusCode = proxy.$statusCode
const $router = useRouter()
// const loginStore = useLoginStore()

interface FormData {
  propOne: string
  propTwo: string
}

// 初始化表单数据
const initFormData = (): FormData => {
  return {
    propOne: null,
    propTwo: null
  }
}

/**
 * 组件事件
 */
const $emit = defineEmits<{
  (e: 'submitSuccess'): void
  (e: 'close'): void
}>()

/**
 * 组件属性
 */
const props = defineProps({
  preparedData: {
    type: Object,
    default: () => {
      return {
        propTwoSelectList: []
      } as {
        propTwoSelectList: any[]
      }
    }
  }
})

const formData = ref<FormData>(initFormData())

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  propOne: [{ required: true, message: '请输入示例一', trigger: 'blur' }],
  propTwo: [
    {
      required: true,
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请选择示例二'))
        } else {
          callback()
        }
      }
    }
  ]
})

const dialogLoading = ref(false)
const btnLoading = ref(false)
const isEdit = ref(false)
const visible = ref(false)

// 提交表单
const onSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      $api.apiModule
        .saveOrUpdate(formData.value)
        .then((res: ResponseData) => {
          if ($statusCode.SUCCESS === res.errorCode) {
            ElMessage.success(res.errorMsg)
            close()
            $emit('submitSuccess')
          } else {
            ElMessage.error(res.errorMsg)
          }
        })
        .catch((err: any) => {
          console.error('onSubmit error: ', err)
        })
        .finally(() => {
          btnLoading.value = false
        })
    }
  })
}

// 获取详情
const getDetail = (id: string) => {
  if (!id) {
    console.error('getDetail error: id 不能为空')
    return
  }
  dialogLoading.value = true
  $api.apiModule
    .getById({ id })
    .then((res: ResponseData) => {
      if ($statusCode.SUCCESS !== res.errorCode || !res.results) {
        return ElMessage.error(res.errorMsg)
      }
      formData.value = res.results
    })
    .catch((err: any) => {
      console.error('getDetail error: ', err)
    })
    .finally(() => {
      dialogLoading.value = false
    })
}

// 打开弹框（弹框打开时调用，一些弹框打开时的初始化处理可以在此方法内进行，譬如：通过 row.id 请求详情...）
const open = (row: FormData) => {
  if (row) {
    isEdit.value = true
    formData.value = {
      ...formData.value,
      ...row
    }
    // 根据 id 获取详情，二选一
    // getDetail(row.id)
  } else {
    isEdit.value = false
  }
  visible.value = true
}

const beforeClose = () => {
  if (btnLoading.value) return
  close()
}

// 关闭弹框
const close = () => {
  if (visible.value) {
    formData.value = initFormData()
    formRef.value?.clearValidate()
    $emit('close')
    visible.value = false
  }
}

defineExpose({
  open,
  close
})
</script>

<style lang="scss" scoped="scoped"></style>
